<?php 
/**
* @package DomBase
* @author Dustin Whittle, Oliver Leisalu
* Easy encryption
*/
class MCrypt {

	private $td;
	
	public function __construct( $key, $iv = false, $algorithm = 'tripledes', $mode = 'ecb') {
		if($mode != 'ecb' && $iv === false) die('In order to use encryption modes other then ecb, you must specify a unique and consistent initialization vector.');
		$this->td = mcrypt_module_open($algorithm, '', $mode, '') ;
		$random_seed = strstr(PHP_OS, "WIN") ? MCRYPT_RAND : MCRYPT_DEV_RANDOM;
		$iv = ($iv === false) ? mcrypt_create_iv(mcrypt_enc_get_iv_size($this->td), $random_seed) : substr($iv, 0, mcrypt_enc_get_iv_size($this->td));
		$expected_key_size = mcrypt_enc_get_key_size($this->td);
		$key = substr(md5($key), 0, $expected_key_size);
		mcrypt_generic_init($this->td, $key, $iv);
	}

	private function mix( $str ) {
		return substr(strrev($str),1,strlen($str)-1).'=';
	}
	
	private function unmix( $str ) {
		return substr(strrev($str),1,strlen($str)-1).'=';
	}

	public function encrypt($plain_string) {
		return ($this->mix(base64_encode(mcrypt_generic($this->td, $plain_string))));
	}

	public function decrypt($encrypted_string) { 
		return trim(mdecrypt_generic($this->td, base64_decode($this->unmix(($encrypted_string)))));
	}

	public function __destruct(){
		mcrypt_generic_deinit($this->td);
		mcrypt_module_close($this->td);
	}
}
?>